$(function() {
	var rows_delete=0;
	var mode="add";
	var m_id=0;
	var emp_id=0;
    var url='controls/salary_model.php';
    var view_flage=0;
	$('#txtDateIn').datepicker();
	
	 $(".txtamt").keypress(function(e) {

        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
	
	initialData();
	$("#btnPrintAll").click(function(e){
		e.preventDefault(); 
		 
		$("#emp_id").val("");
		$("#frmSalaryReport").get(0).setAttribute('action', 'rpt_emp_salary.php');
		 
		$("#frmSalaryReport").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
	});
	$(".btnPrint").live('click',function(e){
		e.preventDefault(); 
		
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		$("#emp_id").val(data[1]);
		$("#frmSalaryReport").get(0).setAttribute('action', 'rpt_emp_salary.php');
		 
		$("#frmSalaryReport").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
	});
	
	$("#btnAddIn").click(function(){
		if (checkControl_In()){
			if (checkDuplicate($("#result_in"),$("#cboName_in").val())){
				var _amt = parseInt($("#txtAmt_in").val());
				var _total= convertToNumber($("#txtTotal").val());
				$("#txtTotal").val(CommaFormatted( (_total + _amt).toFixed(2) ));
				
				$("#result_in").dataTable().fnAddData([
					0,  $("#cboName_in").val() , emp_id , $("#cboName_in option:selected").text(), $("#txtAmt_in").val()
				]);
			}
			$("#txtAmt_in").val("");
		}
	});
	
	$("#btnAddOut").click(function(){
		if (checkControl_Out()){
			if (checkDuplicate($("#result_out"),$("#cboName_out").val())){
			
				var _amt = parseInt($("#txtAmt_out").val());
				var _total= convertToNumber($("#txtTotal").val());
				$("#txtTotal").val(CommaFormatted( (_total- _amt).toFixed(2) ));
				
				$("#result_out").dataTable().fnAddData([
					0,  $("#cboName_out").val() , emp_id , $("#cboName_out option:selected").text(), $("#txtAmt_out").val()
				]);
			}
			$("#txtAmt_out").val("");
		}
	});
	 function checkDuplicate(table,id){
        
            var rows = table.dataTable().fnGetNodes();

            for (var i = 0; i < rows.length; i++)
            {
                 var row_data = table.dataTable().fnGetData(rows[i]);
                if (row_data[1] == id){	
					alert("ซ้ำกับข้อมูลที่อยู่");
					return false;
                }
            }
          
             return true;
    }
	function LoadData(month,code,name,sid,did){
	 
        $( "#resultData tbody tr" ).remove();
        
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			"bAutoWidth": false,
			"bLengthChange": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" },
								{"name":"code","value":code},
								{"name":"name","value":name},
								{"name":"status","value":sid},
								{"name":"depart","value":did},
								{"name":"month","value":month}
							);
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
			 	{  "bSortable": true , "aTargets": [ 2 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 3 ] ,"sClass":"left"},	
				{   "bSortable": true, "aTargets": [ 4 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 5 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 6 ], "sClass":"center" },
				{   "bSortable": true, "aTargets": [ 7 ], "sClass":"center" },
				{   "bSortable": true, "aTargets": [ 8 ], "sClass":"center" },
				
				{ "aTargets": [ 9 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_it==1)
							return "<a href='#popup' data-toggle='modal'><img src='img/page_table_chart_32.png' class='btnEdit' style='cursor:pointer;'/><img src='img/view.png' class='btnView' style='display:none;cursor:pointer;'/></a>";
						else 
							return "";
						}
						
				} 
				,{ "aTargets": [ 10 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						return "<a href='#'  ><img src='img/print2.png' class='btnPrint' style='cursor:pointer;'/></a>";
					}
				} 
			],"fnDrawCallback": function ( oSettings ) {
				 var that = this;
				/* Need to redo the counters if filtered or sorted */
                 var iTotalRecords = oSettings.fnRecordsTotal();
				//alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					 
				} 
		 } );
		 
      }
 
	function initialData(){
		$.get(url, {"m":"curr_month"},function(data){
			//	var obj=eval('('+data+')');	
			$("#month_level").html(data);
		});
		
		$.get(url, {"m":"dy"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboDepartment").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
		});
	
		$.get(url, {"m":"gy"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboStatus").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
		});
	
		$.get(url, {"m":"g"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboStatus_s").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
		});
		$("#cboStatus_s").append($('<option></option>').val(0).html(''));
	
		$.get(url, {"m":"d"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboDepartment_s").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
		});
		$("#cboDepartment_s").append($('<option></option>').val(0).html(''));
	
		$.get(url,{"m":"in"} ,function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboName_in").append(
							$('<option></option>').val(index).html(text)
						 );
				});
			}
		});
		
		$.get(url,{"m":"out"} ,function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboName_out").append(
							$('<option></option>').val(index).html(text)
						 );
				});
			}
		});
		$.get(url, {"m":"m"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboMonth").append(
							$('<option></option>').val(index).html(index)
						 );
				});
			LoadData($("#cboMonth").val(),'','',0,0);	
			}
		});
 
	}
	$("#btnProcess").click(function(){
		$("#popup_monthly").modal('hide');
	});
	$("#btnMonthly").click(function(){
		$.get(url, {"m":"next_month"},function(data){
			$("#txtNextMonth").val(data);
		});
	});
	$("#btnProcess_Confirm").click(function(){
		
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"update_salary"},
				 success: function(data){
					$("#cboMonth").find('option').remove();	
					
					$.get(url, {"m":"curr_month"},function(data){
						$("#month_level").html(data);
					});
					
					$.get(url, {"m":"m"},function(data){
						var obj=eval('('+data+')');	
						if (obj != null){
							$.each(obj, function(index, text) {
								$("#cboMonth").append(
										$('<option></option>').val(index).html(index)
									 );
							});
						LoadData($("#cboMonth").val(),'','',0,0);	
						}
					});
					$("#popupProcess").modal('hide');
				 }
			}); 
		
	});
	$("#cboMonth").change(function(){
		var _m = $(this).val();
		var _str_m = $("#month_level").html();
		
		if (_m != _str_m){
			$('#resultData').find('thead > tr:eq(0) > th:eq(8)').html('แสดงข้อมูล');
			$(".btnEdit").hide();
			$(".btnView").show();
			$(".btnPrint").hide();
			$(".hidden_control").hide();
		}else{
			$('#resultData').find('thead > tr:eq(0) > th:eq(8)').html('เงินเดือน');
			$(".btnEdit").show();
			$(".btnView").hide();
			$(".btnPrint").show();
			$(".hidden_control").show();
		}
	 
		
	});
	function checkControl_In() {
        var bln = true;
        if ($("#txtAmt_in").val() == "" || $("#txtAmt_in").val()==0 ) {
            $("#txtAmt_in").attr('style', "width:100px;background-color:#fddedb;border:1px solid #f99891");
            bln = bln && false;
        } else {
            $("#txtAmt_in").removeAttr('style');
			 $("#txtAmt_in").attr('style', "width:100px;");
            bln = bln && true;
        }
        
        return bln;
    }
	function checkControl_Out() {
        var bln = true;
        if ($("#txtAmt_out").val() == "" || $("#txtAmt_out").val()==0 ) {
            $("#txtAmt_out").attr('style', "width:100px;background-color:#fddedb;border:1px solid #f99891");
            bln = bln && false;
        } else {
            $("#txtAmt_out").removeAttr('style');
			 $("#txtAmt_out").attr('style', "width:100px;");
            bln = bln && true;
        }
        
        return bln;
    }
	
	$("#btnSearch").click(function(){
		var _code = $("#txtCode_s").val();
		var _name = $("#txtName_s").val();
		var _sid = $("#cboStatus_s").val();
		var _did = $("#cboDepartment_s").val();
		var _month = $("#cboMonth").val();
		LoadData(_month,_code,_name,_sid,_did);
	});
	
	$("#btnSave").live('click',function(){
		var list = [];
		var _mode="add";
		if (emp_id!=0)
		{
			_mode="update";
		}
		var rows = $('#result_in').dataTable().fnGetNodes();
		//Add 
		for (var i = 0; i < rows.length; i++)
		{
			var row_data = $('#result_in').dataTable().fnGetData(rows[i]);
			list.push({'o_id': row_data[1],
				'emp_salary_id':row_data[2],
				'amount': row_data[4].replace(',',''),
				'type': 'A'
				});
		}
		//Remove
		rows = $('#result_out').dataTable().fnGetNodes();
		for (var i = 0; i < rows.length; i++)
		{
			var row_data = $('#result_out').dataTable().fnGetData(rows[i]);
			list.push({'o_id': row_data[1],
				'emp_salary_id':row_data[2],
				'amount': row_data[4].replace(',',''),
				'type': 'D'
				});
		}
		
		if (list.length > 0){
			 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":_mode,"id":m_id,"emp_id":emp_id,'list':list,'month':$("#month_level").html()},
				 success: function(data){
				
					$("#popup").modal('hide');
				 }
			}); 
		}
		
			
	});		
	 
		
	//Popup confirm delete
	$(".btnDel").live('click',function(){
		var rows = $(this).closest("tr").get(0);
		rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

	}); 
	
	$("#btnDelete").live('click', function(){
		 
		var row_id =$('#resultData').dataTable().fnGetData(rows_delete);
		
		var id=row_id[1];
		 
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"del","id":id},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					
					$('#resultData').dataTable().fnDeleteRow( rows_delete );
					$('#resultData').dataTable().fnDraw();
				 }
			 });
 
	}); 
	
	$(".btnDel_detail_in").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#result_in').dataTable().fnGetPosition(rows);
		var data =$('#result_in').dataTable().fnGetData(rows);
		var _total= convertToNumber($("#txtTotal").val());
		var _num = convertToNumber(data[4]);
		
		$("#txtTotal").val(CommaFormatted( (_total-_num).toFixed(2) ));
		
        $('#result_in').dataTable().fnDeleteRow(rows_delete);
        $('#result_in').dataTable().fnDraw();
    });
	
	$(".btnDel_detail_out").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#result_out').dataTable().fnGetPosition(rows);
		
		var data =$('#result_out').dataTable().fnGetData(rows);
		var _total= convertToNumber($("#txtTotal").val());
		var _num = convertToNumber(data[4]);
		
		$("#txtTotal").val(CommaFormatted( (_total + _num).toFixed(2) ));
		
        $('#result_out').dataTable().fnDeleteRow(rows_delete);
        $('#result_out').dataTable().fnDraw();
    });
	$(".btnView").live('click',function(){
		mode="view";
		$(".group_control").hide();
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		m_id = data[1];
	 
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"detail","id":m_id,'month':$("#cboMonth").val()},
				 success: function(data){
				 
					 var obj=eval('('+data+')');	
					  emp_id = obj['detail']['emp_id'];
					 
					 $("#emp_code").html(obj['detail']['code']);
					 $("#emp_name").html(obj['detail']['title'] + " " + obj['detail']["name"]);
					 $("#emp_position").html(obj['detail']['departmentname']);
					 $("#txtTotal").val(CommaFormatted(obj['detail']['grand_total']));
					 var in_obj = obj['in'];
					 var out_obj = obj['out'];
					 SetTableIncome(in_obj);
					 SetTableOutcome(out_obj);
				 }
		}); 
	});
	$(".btnEdit").live('click',function(){
		mode="edit";
		$(".group_control").show();
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		m_id = data[1];
	 
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"detail","id":m_id,'month':$("#cboMonth").val()},
				 success: function(data){
				 
					 var obj=eval('('+data+')');	
					  emp_id = obj['detail']['emp_id'];
					 
					 $("#emp_code").html(obj['detail']['code']);
					 $("#emp_name").html(obj['detail']['title'] + " " + obj['detail']["name"]);
					 $("#emp_position").html(obj['detail']['departmentname']);
					 $("#txtTotal").val(CommaFormatted(obj['detail']['grand_total']));
					 var in_obj = obj['in'];
					 var out_obj = obj['out'];
					 SetTableIncome(in_obj);
					 SetTableOutcome(out_obj);
				 }
		}); 
	});
	 
    function SetTableIncome(obj) {
        $("#result_in").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
            "bPaginate": false,
            "bLengthChange": false,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
             "sAjaxDataProp": "in",
			  "aaData": obj,
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
			    {"bVisible": false, "aTargets": [2]},
                {"bSortable": true, "aTargets": [3], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-right"},
                {"aTargets": [5],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						    if (full[5]=='N' ||   (mode=='view'))
							return "";
							else 
                            return "<a href='#'  ><img src='img/delete.png' class='btnDel_detail_in' style='cursor:pointer;'/></a>";
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });

    }	 
	
	function SetTableOutcome(obj) {
        $("#result_out").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
            "bPaginate": false,
            "bLengthChange": false,
            
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
               "sAjaxDataProp": "out",
			  "aaData": obj,
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
				 {"bVisible": false, "aTargets": [2]},
                {"bSortable": true, "aTargets": [3], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-right"},
                {"aTargets": [5],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
							if (mode=='edit')
                            return "<a href='#'  ><img src='img/delete.png' class='btnDel_detail_out' style='cursor:pointer;'/></a>";
							else 
							return "";
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });

    }
	
	function CommaFormatted(amount){
		 
			var delimiter = ","; // replace comma if desired
			var a = amount.split('.',2)
			var d = a[1];
			var i = parseInt(a[0]);
			if(isNaN(i)) { return ''; }
			var minus = '';
			if(i < 0) { minus = '-'; }
			i = Math.abs(i);
			var n = new String(i);
			var a = [];
			while(n.length > 3)
			{
				var nn = n.substr(n.length-3);
				a.unshift(nn);
				n = n.substr(0,n.length-3);
			}
			if(n.length > 0) { a.unshift(n); }
			n = a.join(delimiter);
			if(d.length < 1) { amount = n; }
			else { amount = n + '.' + d; }
			amount = minus + amount;
			return amount;
		}	
    
	function convertToNumber(num){
		var value=0;
		num=num.replace(',','');
		if (!(isNaN(num))){
			value= parseFloat( num , 10);
		}
		return value;
	}
});


